<?php
namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Library\OSS;
use App\Modules\Good\Models\Good;
use App\Modules\Good\Models\GoodsDiscount;
use App\Modules\Package\Models\GoodPackage;
use App\Modules\Shop\Shop;
use App\Modules\User\Models\User;
use Carbon\Carbon;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class CommonController extends Controller
{
    public function updateLoad(Request $request)
    {
        $type = $request->input('type', 'image_upload');
        $r = $request->file();

        $files = Arr::flatten($request->allFiles());
        $data = [];
        foreach ($files as $file) {
            $id = uniqid();
            $key = $type."/".Carbon::now()->timestamp."/".$id.".".$file->getClientOriginalExtension();
            $oss = OSS::instance();
            $oss->storeFile($key, $file->path());
            $data[] = [
                'id' => $id,
                'key' => $key,
                'url' => $oss->getUrl($key),
            ];
        }
        return response()->json($data);
    }

    public function overview()
    {
        // return view('overview', compact('schedule', 'reservation', 'medical', 'reservationCourse', 'todayCourseOrder', 'yesterdayCourseOrder', 'todayExaminationOrder', 'yesterdayExaminationOrder', 'reachStore'));
        return view('overview');
    }

    public function checkAuthorize()
    {
        return view('authority');
    }

    public function passwordForm()
    {
        return view('password');
    }

    public function updatePassword(Request $request)
    {
        $old_pwd = $request->input('old_pwd', '');
        $new_pwd = $request->input('new_pwd', '');
        $re_pwd  = $request->input('re_pwd', '');

        if ($old_pwd == '') return redirect()->back()->withErrors('请输入原密码');
        if ($new_pwd == '') return redirect()->back()->withErrors('请输入新密码');
        if ($new_pwd != $re_pwd)  return redirect()->back()->withErrors('两次密码输入不一致');

        $pattern = '/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{8,16}$/';
        if (!preg_match($pattern, $new_pwd)) return redirect()->back()->withErrors('密码必须由8-16位的数字、字母组成（不能是纯数字）');

        $user = Auth::user();
        if (!Hash::check($old_pwd, $user->password)) return redirect()->back()->withErrors('旧密码输入错误！');

        $password = $new_pwd;

        $user->password = Hash::make($password);

        $user->setRememberToken(Str::random(60));

        $user->save();

        event(new PasswordReset($user));

        Auth::guard('admin')->login($user);
        return redirect()->route('admin.password.from')->with('success', "修改成功");
    }

    public function searchShops(Request $request)
    {
        $term = $request->input('term');
        $query = Shop::query();
        $query->where('status', 'open');
        if (!empty($term)) {
            $query->where('name', 'like', "%".$term."%");
        }
        $re = $query
            ->get()
            ->pluck('name', 'id')
            ->all();
        
        return $re;
    }

    public function searchCategory(Request $request)
    {
        $id = $request->input('shop_id');
        /** @var Shop $shop */
        $shop = Shop::query()->find($id);
        $re = [];
        foreach ($shop->category as $item) {
            $re[$item] = $item;
        }
        return $re;
    }

    public function searchShopGood(Request $request)
    {
        $shopId = $request->input('shop_id');
        $term = $request->input('term');
        $shop = Shop::query()->find($shopId);
        if ($shop->type == Shop::TYPE_PHOTO) {
            $query = GoodPackage::query()
                ->where('shop_id', $shopId);
        } else {
            $query = Good::query()
                ->where('shop_id', $shopId);
        }
        if (!empty($term)) {
            $query->where('name', 'like', "%".$term."%");
        }
        $re = $query
            ->where('status', Good::STATUE_ON)
            ->get()
            ->pluck('name', 'id')
            ->all();
        return $re;
    }

    public function searchTypeGood(Request $request)
    {
        $type = $request->input('type');
        $shopId = $request->input('shop_id');
        $term = $request->input('term');
        if ($type == 'package') {
            $query = GoodPackage::query();
        } else {
            $query = Good::query();
        }
        if (!empty($term)) {
            $query->where('name', 'like', "%".$term."%");
        }
        if (!empty($shopId)) {
            $query->where('shop_id', $shopId);
        }
        $re = $query
            ->where('status', Good::STATUE_ON)
            ->get()
            ->pluck('name', 'id')
            ->all();
        return $re;
    }
    public function searchUser(Request $request)
    {
        $search = $request->input('term');
        $level = $request->input('level');
        $query = User::query()
            ->limit(50);

        if (!empty($search)) {
            $query->where(function ($q) use ($search) {
                return $q->where('mobile', "like", "%".$search."%")
                    ->orWhere('name', 'like', "%".$search."%");
            });
        }
        if (!empty($level)) {
            $query->where('level', $level);
        }
        $user = $query->get();
        $re = [];
        foreach ($user as $item) {
            $re[$item->id] = $item->name."（".$item->mobile."）";
        }
        return $re;
    }

    public function searchPackage(Request $request)
    {
        $search = $request->input('term');
        $shop_id = $request->input('shop_id');
        $query = GoodPackage::query()
            ->where('status', GoodPackage::STATUS_ON)
            ->limit(500);
        if (!empty($search)) {
            $query->where('name', 'like', "%".$search."%");
        }
        if (!empty($shop_id)) {
            $query->where('shop_id', $shop_id);
        }
        $re = $query->get()
            ->pluck('name', 'id');
        return $re;
    }

    public function searchGoods(Request $request)
    {
        $search = $request->input('term');
        $shop_id = $request->input('shop_id');
        $query = Good::query()
            ->where('status', Good::STATUE_ON)
            ->limit(500);
        if (!empty($search)) {
            $query->where('name', "like", "%".$search."%");
        }
        if (!empty($shop_id)) {
            $query->where('shop_id', $shop_id);
        }
        $re = $query->get()
            ->pluck('name', 'id');
        return $re;
    }

    public function searchPackage1(Request $request)
    {
        $search = $request->input('term');
        $shop_id = $request->input('shop_id');
        $query = GoodPackage::query()
            ->where('status', GoodPackage::STATUS_ON)
            ->limit(500);
        if (!empty($search)) {
            $query->where('name', 'like', "%".$search."%");
        }
        if (!empty($shop_id)) {
            $query->where('shop_id', $shop_id);

            // 查询参与满减活动的商品id
            $full_reduction_ids    = DB::table('full_reductions')->where('shop_id', $shop_id)->pluck('id')->all();
            $full_reduction_scopes = DB::table('full_reduction_scopes')->whereIn('full_reduction_id', $full_reduction_ids)->pluck('link_id')->all();

            // 查询参与折扣活动的商品id
            $goods_discount_ids    = DB::table('goods_discounts')->where('shop_id', $shop_id)->pluck('id')->all();
            $goods_discount_scopes = DB::table('goods_discount_scopes')->whereIn('goods_discount_id', $goods_discount_ids)->pluck('link_id')->all();
                
            // 合并数组，查询所有正在营销活动中的商品id
            $in_activity_ids = array_merge($full_reduction_scopes, $goods_discount_scopes);
            $query->whereNotIn('id', $in_activity_ids);
        }

        
        $re = $query->get()
            ->pluck('name', 'id');
        return $re;
    }

    public function searchGoods1(Request $request)
    {
        $search = $request->input('term');
        $shop_id = $request->input('shop_id');
        $query = Good::query()
            ->where('status', Good::STATUE_ON)
            ->limit(500);
        if (!empty($search)) {
            $query->where('name', "like", "%".$search."%");
        }
        if (!empty($shop_id)) {
            $query->where('shop_id', $shop_id);

            // 查询参与满减活动的商品id
            $full_reduction_ids    = DB::table('full_reductions')->where('shop_id', $shop_id)->pluck('id')->all();
            $full_reduction_scopes = DB::table('full_reduction_scopes')->whereIn('full_reduction_id', $full_reduction_ids)->pluck('link_id')->all();

            // 查询参与折扣活动的商品id
            $goods_discount_ids    = DB::table('goods_discounts')->where('shop_id', $shop_id)->pluck('id')->all();
            $goods_discount_scopes = DB::table('goods_discount_scopes')->whereIn('goods_discount_id', $goods_discount_ids)->pluck('link_id')->all();
                
            // 合并数组，查询所有正在营销活动中的商品id
            $in_activity_ids = array_merge($full_reduction_scopes, $goods_discount_scopes);
            $query->whereNotIn('id', $in_activity_ids);
        }
        $re = $query->get()
            ->pluck('name', 'id');
        return $re;
    }

    public function getShopType(Request $request)
    {
        $shop_id = $request->input('shop_id');
        $shop = Shop::query()->where('id', $shop_id)->first(['type','name','id']);
        return $shop;
    }
}
